package ext.tianma.bom.workflow;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import ext.tianma.bom.service.SelectPartService;
import ext.tianma.util.IbaAttributeUtil;
import ext.tianma.util.PropertiesUtil;
import ext.tianma.util.TianMaConstants;
import wt.doc.WTDocument;
import wt.fc.ObjectReference;
import wt.fc.QueryResult;
import wt.fc.collections.WTArrayList;
import wt.mail.EMailMessage;
import wt.part.WTPart;
import wt.util.WTException;
import ext.tianma.bom.workflow.ReWriteConversionThroughputBusiness;
/**
 * 设计量产发布,erp发布之后,邮件通知
 * 
 * @author laichao_sun
 *
 */

public class SendEmailNotification {
	public static String configFilePath = "codebase" + File.separator + "ext" + File.separator + "tianma"
			+ File.separator + "cfg" + File.separator + "TianmaPro.properties";

	public static boolean sendEmailNotification(Object obj, WTArrayList reviewObjs) {
		System.out.println("SLC====>进入计划转量产邮件发送");
		WTDocument doc = null;
		if (obj == null) {
			return false;
		}
		if (obj instanceof ObjectReference) {
			ObjectReference ref = (ObjectReference) obj;
			obj = ref.getObject();
		}

		if (obj instanceof WTDocument) {
			doc = (WTDocument) obj;
		}

		if (doc != null && !"".equals(doc)) {
			try {
				PropertiesUtil ut = new PropertiesUtil(configFilePath);
				String email = ut.getValueByKey("Plan_conversion_email");
				String Email = "";
				String[] drawing = email.split(";");

				
				String titleStr = "设计转量产已发布";
				
				
				//获取文档的关联部件
				WTArrayList partlist =getAllRelatedParts(doc);
				
				
				
				String content = content(partlist);
				if (content == null) {
					System.out.println("设计转量产已发布,部件没有深圳的或不是量产发布的部件,所以不发邮件");
					return false;
				}
				//System.out.println("邮件信息:" + content);
				for (int i = 0; i < drawing.length; i++) {
					Email = drawing[i];
					System.out.println("邮箱:" + Email);
					sendEmail(Email, content, titleStr);
				}
				// boolean flag = sendEmail(email,content,titleStr);

				return true;

			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}

		}
		return false;
	}
	
	//通过文档获取所关联的所有零部件
	private static WTArrayList getAllRelatedParts( WTDocument doc ) throws WTException {
		WTArrayList allPart = new WTArrayList();
		
		//获取当前文档所关联的所有零部件
	    QueryResult refPartQR = ext.com.core.CoreUtil.getAssociatedParts(doc);
	    
	    while (refPartQR.hasMoreElements()) {
			Object refObj = refPartQR.nextElement();
			
			if (refObj !=null && refObj instanceof WTPart) {
			    WTPart part = (WTPart) refObj;
			    
			    System.out.println("关联部件的编号:"+part.getNumber()+" | "+part.getViewName());
			    //将文档关联的零部件加入List
			    allPart.add(part);
			    
			 	//递归获得所有的子部件
		    	//ArrayList<WTPart> allSubPart = BOMBusinessUtil.getAllSubPart(part);
			    //List<WTPart> allSubPart = getAllSubParts( part ) ;
			    
			    //包含特地替代料
			   // List<WTPart> allSubPart = ReWriteBOMReviewConfirmBusiness.getAllSubPartsWithSubstitute(part) ;
			    
		    	//System.out.println("指定对象【"+part.getDisplayIdentifier()+"】下包含的所有子部件个数是："+allSubPart.size());
		    	
		    	//将所有子件加入List
		    	//allPart.addAll(allSubPart);
			}
	    }
	    
	    return allPart ;
	}
	

	// 拼接成品的信息,作为邮件的信息
	public static String content(WTArrayList partlist) throws WTException {
		String infoPage = "";
		String number = "";
		String url = "";
		String state = "";
		String name = "";
		String content = "";
		partlist = BOMBusinessUtil.getLatestWTPartByView(partlist);
		for (int i = 0; i < partlist.size(); i++) {
			ObjectReference partref = (ObjectReference) partlist.get(i);
			Object partobj = partref.getObject();
			WTPart part = (WTPart) partobj;

			boolean flag = checkEffectiveSite(part);
			if (flag) {
				continue;
			}
			// 部件的生命周期
			state = part.getLifeCycleState().getDisplay(Locale.CHINA);
			if (!("量产发布".equals(state))) {
				continue;
			}
			// 物料编码
			number = part.getNumber();
			// 物料的详细信息的url了
			url = SelectPartService.generateInfoPageURL(part);
			infoPage = "<a target='_blank' href='" + url + "'>" + "点击查看详情" + "</a><br/>";

			// 部件的名字
			name = part.getName();

			//System.out.println("number:" + number + "||url+" + url + "||生命周期:" + state + "||名字:" + name);
			content += "<tr><td style=\"padding:.75pt .75pt .75pt .75pt\">\r\n" + "<p style=\"margin:0cm;\r\n"
					+ "	margin-bottom:.0001pt;\r\n" + "	font-size:12.0pt;\r\n"
					+ "	font-family:宋体;text-align:center\" align=\"center\"><b>" + number
					+ "<span lang=\"EN-US\"></span></b></p>\r\n"
					+ "</td><td style=\"padding:.75pt .75pt .75pt .75pt\">\r\n" + "<p style=\"margin:0cm;\r\n"
					+ "	margin-bottom:.0001pt;\r\n" + "	font-size:12.0pt;\r\n"
					+ "	font-family:宋体;text-align:center\" align=\"center\"><b>" + name
					+ "<span lang=\"EN-US\"></span></b></p>\r\n"
					+ "</td><td style=\"padding:.75pt .75pt .75pt .75pt\">\r\n" + "<p style=\"margin:0cm;\r\n"
					+ "	margin-bottom:.0001pt;\r\n" + "	font-size:12.0pt;\r\n"
					+ "	font-family:宋体;text-align:center\" align=\"center\"><b>" + state
					+ "<span lang=\"EN-US\"></span></b></p>\r\n"
					+ "</td><td style=\"padding:.75pt .75pt .75pt .75pt\">\r\n" + "<p style=\"margin:0cm;\r\n"
					+ "	margin-bottom:.0001pt;\r\n" + "	font-size:12.0pt;\r\n"
					+ "	font-family:宋体;text-align:center\" align=\"center\"><b>" + infoPage
					+ "<span lang=\"EN-US\"></span></b></p>\r\n" + "</td></tr>";
			// content += "成品编码为" + number + "，" +"名称为" + name + "，" + "状态为" + state
			// +""+infoPage;
		}
		if ("".equals(content)) {
			return null;
		}
		content = "<table class=\"MsoNormalTable\" border=\"1\" cellpadding=\"0\">\r\n"
				+ "<tbody><tr><td style=\"padding:.75pt .75pt .75pt .75pt\">\r\n" + "<p style=\"margin:0cm;\r\n"
				+ "	margin-bottom:.0001pt;\r\n" + "	font-size:12.0pt;\r\n"
				+ "	font-family:宋体;text-align:center\" align=\"center\"><b>成品编号<span lang=\"EN-US\"></span></b></p>\r\n"
				+ "</td><td style=\"padding:.75pt .75pt .75pt .75pt\">\r\n" + "<p style=\"margin:0cm;\r\n"
				+ "	margin-bottom:.0001pt;\r\n" + "	font-size:12.0pt;\r\n"
				+ "	font-family:宋体;text-align:center\" align=\"center\"><b>成品名称<span lang=\"EN-US\"></span></b></p>\r\n"
				+ "</td><td style=\"padding:.75pt .75pt .75pt .75pt\">\r\n" + "<p style=\"margin:0cm;\r\n"
				+ "	margin-bottom:.0001pt;\r\n" + "	font-size:12.0pt;\r\n"
				+ "	font-family:宋体;text-align:center\" align=\"center\"><b>成品状态<span lang=\"EN-US\"></span></b></p>\r\n"
				+ "</td><td style=\"padding:.75pt .75pt .75pt .75pt\">\r\n" + "<p style=\"margin:0cm;\r\n"
				+ "	margin-bottom:.0001pt;\r\n" + "	font-size:12.0pt;\r\n"
				+ "	font-family:宋体;text-align:center\" align=\"center\"><b>详细页面<span lang=\"EN-US\"></span></b></p>\r\n"
				+ "</td></tr>" + content + "</tbody>\r\n" + "</table>\r\n" + "</div>\r\n"
				+ "<p class=\"MsoNormal\"><span lang=\"EN-US\" style=\"font-size:10.0pt;font-family:&quot;Calibri&quot;,&quot;sans-serif&quot;\"><o:p>&nbsp;</o:p></span></p>\r\n"
				+ "</div>\r\n"
				+ "<div class=\"MsoNormal\" align=\"center\" style=\"text-align:center\"><span lang=\"EN-US\" style=\"font-size:12.0pt;font-family:宋体\">\r\n"
				+ "<hr size=\"2\" width=\"100%\" align=\"center\">\r\n" + "</span></div>\r\n"
				+ "<p class=\"MsoNormal\" align=\"left\" style=\"text-align:left\"><span style=\"font-size:9.0pt;font-family:宋体;color:gray\">“</span><span lang=\"EN-US\" style=\"font-size:9.0pt;font-family:&quot;Arial&quot;,&quot;sans-serif&quot;;color:gray\">This e-mail message together with any attachments\r\n"
				+ " thereto (if any) is confidential, intended only for the use of the named recipient(s) above. Any unauthorized review, use, copying, disclosure, or distribution of any information contained in or attached to this transmission is STRICTLY PROHIBITED. If you\r\n"
				+ " have received this message in error, or are not the named recipient(s), please immediately notify the sender and delete this e-mail message and any attached documentation from your computer. Thank you!<br>\r\n"
				+ "</span><span style=\"font-size:9.0pt;font-family:宋体;color:gray\">本电子邮件及附件（如有）所载信息均为保密信息，仅供指定收件人使用。未经授权者收到此信息均无权阅读、使用、复制、揭露或散布。若您误收到本电子邮件或非本电子邮件的指定收件人，请立即通知发件人并从电脑中删除该电子邮件及其附件。谢谢！”</span></p>\r\n"
				+ "\r\n";
		return content;
	}

	// 检验料号生效地是否有产地C01/02、04、08
	private static boolean checkEffectiveSite(WTPart part) {
		List<String> effectiveSite = IbaAttributeUtil.getAttributeValues(part, "partNumberEffectiveSite");
		boolean temp = true;
		for (String site : effectiveSite) {
			if (site.contains(TianMaConstants.EffectiveSite.C01.getSite())
					|| site.contains(TianMaConstants.EffectiveSite.C02.getSite())
					|| site.contains(TianMaConstants.EffectiveSite.C04.getSite())
					|| site.contains(TianMaConstants.EffectiveSite.C08.getSite())) {
				temp = false;
				break;
			}
		}
		return temp;
	}

	/**
	 * 发送邮件
	 * 
	 * @param userName
	 * @param content
	 * @param titleStr
	 * @return
	 */
	public static boolean sendEmail(String emailAddr, String content, String titleStr) {
		try {
			System.out.println("emailAddr======" + emailAddr);
			// 邮件内容
			StringBuffer body = new StringBuffer();
			body.append(content);
			String[] emailSendTo = "".equals(emailAddr) || emailAddr == null ? null : emailAddr.split(";");// 2、why？
			EMailMessage email = EMailMessage.newEMailMessage();
			email.addEmailAddress(emailSendTo);
			// 邮件主题
			StringBuffer title = new StringBuffer();
			title.append(titleStr);
			email.setSubject(title.toString());
			email.setMultipartSubtype("text/html;charset=\"UTF8\"");
			email.addPart(body.toString(), "text/html;charset=\"UTF8\"");
			email.send(false);
			return true;
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}

	}
}
